#include "IntermBuffer.hpp"

IntermBuffer::IntermBuffer(int slots)
{
  this->slots = slots; 
  this->buffers = new list<pair<string, string> >[slots];
  this->buflocks = new pthread_mutex_t[slots]; 
  this->bufsize = new unsigned long[slots]; 
  for (int i = 0; i < slots; i++)
    {
      pthread_mutex_init(&this->buflocks[i], NULL);
      this->bufsize[i] = 0; 
    }
}

IntermBuffer::~IntermBuffer()
{
  delete []this->buffers; 
  delete []this->buflocks;
  delete []this->bufsize; 
}

unsigned long IntermBuffer::entrySize(pair<string, string>& p)
{
  return p.first.size() + p.second.size() + 3; 
}

void IntermBuffer::addEntry(int slot, pair<string, string> p)
{
  pthread_mutex_lock(&this->buflocks[slot]);
  this->buffers[slot].push_back(p); 
  this->bufsize[slot] += this->entrySize(p); 
  pthread_mutex_unlock(&this->buflocks[slot]);
}

list<pair<string, string> >& IntermBuffer::getBuffer(int slot)
{
  return this->buffers[slot]; 
}

void IntermBuffer::print()
{
  for (int b = 0; b < this->slots; b++)
    {
      list<pair<string, string> >::const_iterator it; 
      for (it = this->buffers[b].begin(); it != this->buffers[b].end(); it++)
	{
	  cout << "[" << (*it).first << "," << (*it).second << "] "; 
	}
      //cout << intermbuf[b].size() << "\n"; 
      cout << "\n(" << this->bufsize[b] << "bytes in "<< this->buffers[b].size() << ")\n"; 
    }
}
